package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class UncompressDataStreamWithGzip {
	private static final int BYTE_BUFFER = 1024;
	private static final String GZIP_FILE_SUFFIX = ".gz";

	public static void ungzip(InputStream is, OutputStream os)
			throws IOException {
		GZIPInputStream gis = new GZIPInputStream(is);

		byte[] data = new byte[BYTE_BUFFER];
		int length = -1;
		while ((length = gis.read(data)) != -1) {
			os.write(data, 0, length);
		}

		gis.close();
	}


	public static byte[] ungzip(byte[] content) throws IOException {
		ByteArrayInputStream bis = new ByteArrayInputStream(content);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		ungzip(bis, bos);

		bos.flush();
		byte[] result = bos.toByteArray();
		bos.close();
		bis.close();

		return result;
	}

	public static boolean ungzip(File gzipFile) {
		return ungzip(gzipFile, true);
	}

	public static boolean ungzip(File gzipFile, boolean deleteSourceFile) {
		String fileName = gzipFile.getName();
		if (fileName.endsWith(GZIP_FILE_SUFFIX)) {
			fileName = fileName.substring(0,
					fileName.lastIndexOf(GZIP_FILE_SUFFIX));
		} else {
			fileName = "ungz-" + fileName;
		}
		File targetFile = new File(gzipFile.getParent(), fileName);
		return ungzip(gzipFile, targetFile, deleteSourceFile);
	}

	public static boolean ungzip(File gzipFile, File targetFile,
	                             boolean deleteSourceFile) {
		BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(gzipFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}

		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(targetFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			try {
				if (bis != null)
					bis.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return false;
		}

		GZIPInputStream gis = null;
		try {
			gis = new GZIPInputStream(bis);
			byte[] data = new byte[BYTE_BUFFER];
			int length = -1;
			while ((length = gis.read(data)) != -1) {
				bos.write(data, 0, length);
			}
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (bos != null)
					bos.close();
				if (gis != null)
					gis.close();
				if (bis != null)
					bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (deleteSourceFile)
			return gzipFile.delete();

		return true;
	}
}
